const crypto = require('crypto');

/**
 * 腾讯云实时语音识别WebSocket签名颁发接口
 * POST /api/voiceforText/voice-signature { userId }
 */
exports.getVoiceSignature = async (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(400).json({ success: false, message: '缺少 userId' });
  }

  // 这里可以加你的用户校验逻辑

  try {
    const appId = process.env.TENCENT_VOICE_APPID;
    const secretId = process.env.TENCENT_VOICE_SECRETID;
    const secretKey = process.env.TENCENT_VOICE_SECRET;

    if (!appId || !secretId || !secretKey) {
      return res.status(500).json({ 
        success: false, 
        message: '服务器配置错误：缺少腾讯云凭证' 
      });
    }

    // 生成签名参数
    const timestamp = Math.floor(Date.now() / 1000);
    const expired = timestamp + 1800; // 30分钟有效期
    const nonce = Math.floor(Math.random() * 10000000000); // 随机正整数
    const voiceId = generateVoiceId(); // 生成唯一voiceId

    // 根据腾讯云实时语音识别WebSocket文档的签名方法
    // 1. 对参数进行字典序排序并拼接
    const params = {
      'engine_model_type': '16k_zh',
      'expired': expired,
      'needvad': 1,
      'nonce': nonce,
      'secretid': secretId,
      'timestamp': timestamp,
      'voice_format': 1,
      'voice_id': voiceId
    };

    // 按字典序排序
    const sortedKeys = Object.keys(params).sort();
    const queryString = sortedKeys.map(key => `${key}=${params[key]}`).join('&');
    
    // 2. 拼接签名原文
    const signStr = `asr.cloud.tencent.com/asr/v2/${appId}?${queryString}`;
    
    // 3. 使用HMAC-SHA1算法进行加密并Base64编码
    const signature = crypto.createHmac('sha1', secretKey)
      .update(signStr)
      .digest('base64');

    // 返回WebSocket连接所需的完整参数
    res.json({
      success: true,
      data: {
        appId: appId,
        secretId: secretId,
        timestamp: timestamp,
        expired: expired,
        nonce: nonce,
        voiceId: voiceId,
        signature: signature,
        // WebSocket连接URL参数
        wsUrl: `wss://asr.cloud.tencent.com/asr/v2/${appId}`,
        // 其他识别参数
        engine_model_type: '16k_zh',
        voice_format: 1,
        needvad: 1,
        voice_id: voiceId,
        // 完整的查询参数（已URL编码）
        queryParams: {
          engine_model_type: '16k_zh',
          expired: expired,
          needvad: 1,
          nonce: nonce,
          secretid: secretId,
          timestamp: timestamp,
          voice_format: 1,
          voice_id: voiceId,
          signature: encodeURIComponent(signature)
        }
      }
    });

  } catch (error) {
    console.error('生成语音识别签名失败:', error);
    res.status(500).json({
      success: false,
      message: '生成签名失败',
      error: error.message
    });
  }
};

/**
 * 生成唯一的voiceId
 */
function generateVoiceId() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 16; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
} 